<template>
	<view class="pages-user-login rel" :class="[{'page-height':!configInfo.plugAuth.coachport}]" v-if="isLoad">
		<block v-if="!configInfo.plugAuth.coachport">
			<abnor type="NOT_AUTH" :isCenter="true"></abnor>
		</block>
		<block v-if="configInfo.plugAuth.coachport">
			<!-- #ifdef H5 -->
			<view @tap="$util.goUrl({url:`/technician/pages/login`,openType:`redirectTo`})" class="abs"
				:class="[{'back-user-ios': configInfo.isIos},{'back-user-android': !configInfo.isIos}]"
				style="margin-top:25rpx;z-index: 999;">
				<view class="icon-left iconfont"></view>
				<view class="back-user_text">返回上页</view>
			</view>
			<!-- #endif -->
			<!-- #ifndef H5 -->
			<view @tap="$util.goUrl({url:1,openType:`navigateBack`})" class="abs"
				:class="[{'back-user-ios': configInfo.isIos},{'back-user-android': !configInfo.isIos}]"
				style="z-index: 999;" :style="{marginTop:`${configInfo.navBarHeight - 40}px`}">
				<view class="icon-left iconfont"></view>
				<view class="back-user_text">返回上页</view>
			</view>
			<!-- #endif -->

			<image class="coach-bg abs" :src="`https://www.peikangbao.cn/admin/anmo/technician/coach-bg.png`"></image>
			<view class="rel" style="padding: 60rpx;">
				<!-- #ifdef H5 -->
				<view style="height:112rpx"></view>
				<!-- #endif -->
				<!-- #ifndef H5 -->
				<view style="height:200rpx"></view>
				<!-- #endif -->
				<!-- <view class="flex-center">
					<image mode="aspectFill" lazy-load class="logo-img radius" :src="configInfo.app_logo"></image>
					<view class="flex-1 ml-md f-lg-title text-bold" style="color: #142C57;">
						{{configInfo.coach_app_text}}
					</view>
				</view> -->

				<view class="flex-warp f-title" style="margin: 0 0 68rpx 0;">
					<view @tap.stop="toChangeTab(index)" class="flex-center rel"
						:style="{color:tabInd==index?'#142C57':'#8A98AF',marginLeft:index==1?'104rpx':''}"
						v-for="(item,index) in ['登录','注册']" :key="index">
						{{item}}
						<view class="line abs" :style="{background:primaryColor}" v-if="tabInd==index"></view>
					</view>
				</view>
				<block v-if="tabInd==0">
					<view class="login-btn flex-center pl-lg pr-lg f-mini-title radius-16">
						<view class="text">手机号</view>
						<view class="flex-1 flex-center">
							<input v-model="loginForm.user_name" class="input flex-1 c-title" type="number"
								maxlength="11" placeholder="请输入手机号" placeholder-style="color:#C2CCD8" />
							<i @tap.stop="toClearName('loginForm')" class="iconfont icon-close"
								v-if="loginForm.user_name&&loginForm.user_name.length==11"></i>
						</view>
					</view>
					<view class="login-btn flex-center mt-md pl-lg pr-lg f-mini-title radius-16">
						<view class="text">密码</view>
						<view class="flex-1 flex-center">
							<block v-if="show_password">
								<input v-model="loginForm.pass_word" class="input flex-1 c-title" type="text"
									maxlength="18" placeholder="请输入密码" placeholder-style="color:#C2CCD8" />
							</block>
							<block v-if="!show_password">
								<input v-model="loginForm.pass_word" class="input flex-1 c-title" type="password"
									maxlength="18" placeholder="请输入密码" placeholder-style="color:#C2CCD8" />
							</block>
							<i @click="show_password = !show_password" class="iconfont pl-sm cursor-pointer" :class="[
					              { iconxianshimima: show_password },
					              { iconyincangmima: !show_password }
					            ]" style="width: 40rpx"></i>
						</view>
					</view>

					<view @tap.stop="submit('login')" class="login-btn flex-center f-title radius-10"
						style="margin: 40rpx 0" :style="{ background: primaryColor ,color:'#fff'}">登录
					</view> 
				</block>
				<block v-if="tabInd==1">
					<view class="login-btn flex-center pl-lg pr-lg f-mini-title radius-16">
						<view class="text">手机号</view>
						<view class="flex-1 flex-center">
							<input v-model="registerForm.user_name" class="input flex-1 c-title" type="number"
								maxlength="11" placeholder="请输入手机号" placeholder-style="color:#C2CCD8" />
							<i @tap.stop="toClearName('registerForm')" class="iconfont icon-close"
								v-if="registerForm.user_name&&registerForm.user_name.length==11"></i>
						</view>
					</view>
					<view class="login-btn flex-center mt-md pl-lg pr-lg f-mini-title radius-16"
						v-if="configInfo.coach_account_phone_status">
						<view class="text">验证码</view>
						<view class="flex-1 flex-center">
							<input v-model="registerForm.phone_code" class="input flex-1 c-title" type="number"
								maxlength="11" placeholder="请输入验证码" placeholder-style="color:#C2CCD8" />
							<view @tap="submit('send')" class="f-mini-title" :style="{color:primaryColor}">
								{{authTime>0?`(${authTime}s)`:'获取验证码'}}
							</view>
						</view>
					</view>
					<view class="login-btn flex-center mt-md pl-lg pr-lg f-mini-title radius-16">
						<view class="text">密码</view>
						<view class="flex-1 flex-center">
							<block v-if="show_password">
								<input v-model="registerForm.pass_word" class="input flex-1 c-title" type="text"
									maxlength="18" placeholder="请输入密码" placeholder-style="color:#C2CCD8" />
							</block>
							<block v-if="!show_password">
								<input v-model="registerForm.pass_word" class="input flex-1 c-title" type="password"
									maxlength="18" placeholder="请输入密码" placeholder-style="color:#C2CCD8" />
							</block>
							<i @click="show_password = !show_password" class="iconfont pl-sm cursor-pointer" :class="[
					              { iconxianshimima: show_password },
					              { iconyincangmima: !show_password }
					            ]" style="width: 40rpx"></i>
						</view>
					</view>
					<view class="login-btn flex-center mt-md pl-lg pr-lg f-mini-title radius-16">
						<view class="text">再次输入</view>
						<view class="flex-1 flex-center">
							<block v-if="show_again">
								<input v-model="registerForm.pass_again" class="input flex-1 c-title" type="text"
									maxlength="18" placeholder="请再次输入密码" placeholder-style="color:#C2CCD8" />
							</block>
							<block v-if="!show_again">
								<input v-model="registerForm.pass_again" class="input flex-1 c-title" type="password"
									maxlength="18" placeholder="请再次输入密码" placeholder-style="color:#C2CCD8" />
							</block>
							<i @click="show_again = !show_again" class="iconfont pl-sm cursor-pointer" :class="[
					              { iconxianshimima: show_again },
					              { iconyincangmima: !show_again }
					            ]" style="width: 40rpx"></i>
						</view>
					</view>
					<view @tap.stop="submit('register')" class="login-btn flex-center f-title radius-10"
						style="margin: 40rpx 0" :style="{ background: primaryColor,color:'#fff' }">立即注册 </view>
				</block>
			</view>
		</block>

		<uni-popup ref="show_rule_item" type="center" :maskClick="false">
			<view class="common-popup-content fill-base pd-lg radius-34 rel" style="padding:50rpx 30rpx">
				<i @tap.stop="$refs.show_rule_item.close()" class="iconfont icon-close abs"
					style="top:20rpx;right:16rpx;font-size: 44rpx;"></i>
				<view class="flex-center flex-column mt-lg">
					<!-- <image class="logo-img md radius" :src="configInfo.app_logo"></image>
					<view class="mt-md f-mini-title c-title text-bold">{{configInfo.coach_app_text}}</view> -->
					<view class="other-sign flex-center rel b-1px-t" style="margin-top: 60rpx;">
						<view class="pl-sm pr-sm f-mini-title flex-center fill-base rel">请选择登录方式</view>
					</view>
					<view class="flex-center mt-md">
						<view @tap.stop="toChooseLogin('weixin')" class="sign-icon-btn flex-center rel radius">
							<view class="sign-icon-btn abs radius" :style="{background:primaryColor}"></view>
							<i class="iconfont icon-weixin" :style="{color:primaryColor}"></i>
						</view>
						<!-- #ifdef APP-PLUS -->
						<view @tap.stop="toChooseLogin('apple')" class="sign-icon-btn flex-center rel radius"
							style="margin-left: 82rpx;" v-if="is_ios_login">
							<view class="sign-icon-btn abs radius" :style="{background:'#333333'}"></view>
							<i class="iconfont icon-apple" :style="{color:'#333333'}"></i>
						</view>
						<!-- #endif -->
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	import siteInfo from '@/siteinfo.js';
	export default {
		components: {},
		data() {
			return {
				isLoad: false,
				options: {},
				is_ios_login: false,
				show_password: false,
				show_again: false,
				lockTap: false,
				tabInd: 0,
				authTime: 0,
				timer: null,
				coachList: [],
				loginForm: {
					user_name: '',
					pass_word: ''
				},
				registerForm: {
					user_name: '',
					phone_code: '',
					pass_word: '',
					pass_again: ''
				},
				loginRule: [{
					name: "user_name",
					checkType: "isMobile",
					errorMsg: "请输入手机号",
					regText: "手机号"
				}, {
					name: "pass_word",
					checkType: "isPassWord",
					errorMsg: "请输入密码",
					regText: "密码"
				}],
				registerRule: [{
					name: "user_name",
					checkType: "isMobile",
					errorMsg: "请输入手机号",
					regText: "手机号"
				}, {
					name: "phone_code",
					checkType: "isNotNull",
					errorMsg: "请输入短信验证码",
					regText: "短信验证码"
				}, {
					name: "pass_word",
					checkType: "isPassWord",
					errorMsg: "请输入密码",
					regText: "密码"
				}, {
					name: "pass_again",
					checkType: "isPassWord",
					errorMsg: "请再次输入密码",
					regText: "密码"
				}],
				sendRule: [{
					name: "user_name",
					checkType: "isMobile",
					errorMsg: "请输入手机号",
					regText: "手机号"
				}]
			}
		},
		async onLoad(options) {
			let {
				tab = 0
			} = options
			tab = this.isRegister ? 1 : tab * 1
			if (tab) {
				this.$util.showLoading()
				this.updateUserItem({
					key: 'isRegister',
					val: true
				})
			}
			options.tab = tab
			this.tabInd = tab
			this.options = options
			this.lockTap = false
			this.initIndex()
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			commonOptions: state => state.user.commonOptions,
			appLogin: state => state.user.appLogin,
			loginType: state => state.user.loginType,
			loginPage: state => state.user.loginPage,
			coachAccountInfo: state => state.user.coachAccountInfo,
		}),
		methods: {
			...mapActions(['getConfigInfo', 'getAccountCoach']),
			...mapMutations(['updateUserItem']),
			async initIndex() {
				// #ifdef H5
				uni.setNavigationBarTitle({
					title: `登录/注册`
				})
				// #endif
				let [syserr, sysinfo] = await uni.getSystemInfo()
				let {
					browserVersion = '',
						platform
				} = sysinfo
				this.is_ios_login = platform === 'ios' && browserVersion.split('.')[0] * 1 > 12
				if (!this.configInfo.id) {
					await this.getConfigInfo()
				}
				let {
					userInfo
				} = this
				if (!this.isLoad && (!userInfo || (userInfo && !userInfo.id))) {
					this.updateUserItem({
						key: 'isGzhLogin',
						val: false
					})
				}
				this.$util.hideAll()
				this.isLoad = true
				// #ifdef H5
				this.$jweixin.hideOptionMenu()
				// #endif
			},
			toChangeTab(index) { 
				if (index == this.tabInd) return
				this.tabInd = index
				this.options.tab = index
				this.updateUserItem({
					key: 'isRegister',
					val: index == 1
				})
				// #ifdef H5
				if (index && !this.autograph) {
					this.toChooseLogin('weixin')
					return
				}
				// #endif
				this.show_password = false
				this.show_again = false
				if (index) {
					this.registerForm = {
						user_name: '',
						phone_code: '',
						pass_word: '',
						pass_again: ''
					}
				} else {
					this.loginForm = {
						user_name: '',
						pass_word: ''
					}
				}
			},
			toClearName(key) {
				let form = this.$util.deepCopy(this[key])
				form.user_name = ''
				this.$nextTick(() => {
					this[key] = form
				}, 0)
			},
			toChooseLogin(type) {
				this.updateUserItem({
					key: 'loginType',
					val: type
				})
				this.lockTap = false
				this.toConfirm()
			},
			toConfirm() { 
				if (this.lockTap) return
				this.lockTap = true
				this.$refs.show_rule_item.close()
				// #ifdef H5
				this.toGzhLogin()
				// #endif	
				// #ifndef H5
				this.toAppLogin()
				// #endif
			},
			// 公众号登录
			async toGzhLogin() {
				let {
					siteroot,
					gzh_appid
				} = siteInfo

				this.updateUserItem({
					key: 'isGzhLogin',
					val: true
				})
				this.updateUserItem({
					key: 'commonOptions',
					val: this.commonOptions
				})

				let {
					coachInfo,
					loginPage
				} = this

				let page = `/pages/coach-index`
				console.log(coachInfo, loginPage, page, "====coachInfo=loginPage=page")
				if (coachInfo && coachInfo.id && coachInfo.id != -1) {
					this.$util.goUrl({
						url: page,
						openType: `reLaunch`
					})
					return
				}
				if (this.tabInd) {
					page = `/technician/pages/account/login?tab=1`
					this.updateUserItem({
						key: 'isRegister',
						val: true
					})
				}
				this.updateUserItem({
					key: 'autograph',
					val: ''
				})
				let coachport = ''
				// #ifdef H5-COACH
				coachport = 'coach/'
				// #endif 
				let url = siteroot.split('/index.php')[0]
				let href = `${url}/${coachport}h5/#${page}`
				let pageUrl = window.location.href;
				let redirect_uri = encodeURIComponent(href)
				let authUrl =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${gzh_appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
				window.location.href = authUrl
			},
			// 小程序、APP登录
			async toAppLogin() {
				let {
					loginType: provider
				} = this

				try {
					let [providerErr, providerData] = await uni.getProvider({
						service: 'oauth',
					});
					if (providerErr) {
						this.$util.showToast({
							title: providerErr.errMsg
						})
						this.lockTap = false
						return
					}
					let [loginErr, loginData] = await uni.login({
						provider
					})
					if (loginErr) {
						this.$util.showToast({
							title: loginErr.errMsg
						})
						this.lockTap = false
						return
					}
					// #ifdef MP-WEIXIN
					let pid = 0
					let coupon_atv_id = 0
					let pageUrl = this.loginPage || `/pages/coach-index`
					if (pageUrl.includes('pid=')) {
						pid = pageUrl.split('pid=')[1].split('&')[0]
					}
					if (pageUrl.includes('coupon_atv_id=')) {
						pid = pageUrl.split('coupon_atv_id=')[1].split('&')[0]
					}
					let userInfo = {
						code: loginData.code,
						pid,
						coupon_atv_id
					}
					// #endif
					// #ifdef APP-PLUS
					let [infoErr, infoData] = await uni.getUserInfo({
						provider
					})
					if (infoErr) {
						this.$util.showToast({
							title: infoErr.errMsg
						})
						this.lockTap = false
						return
					}
					let {
						userInfo = {}
					} = infoData
					let {
						openId = ''
					} = userInfo
					if (!openId) {
						this.lockTap = false
						return
					}
					// #endif

					this.$util.showLoading({
						title: "登录中..."
					})
					try {
						let param = {
							// #ifdef MP-WEIXIN
							type: 1,
							// #endif
							// #ifndef MP-WEIXIN
							type: provider == 'weixin' ? 2 : 3,
							// #endif
							param: {
								data: userInfo
							},
							init: 1
						}
						this.toConfirmLogin(param)
					} catch (e) {
						this.$util.hideAll()
						this.lockTap = false
					}
				} catch (e) {
					this.$util.showToast({
						title: `没有获取到用户信息，请确认已登录`
					})
					this.lockTap = false
				}
			},
			async toConfirmLogin(login_params) {
				let {
					loginType
				} = this

				let {
					type,
					param,
					init = 0
				} = login_params

				// #ifdef MP-WEIXIN
				param = param.data
				// #endif

				// #ifdef MP-WEIXIN-COACH
				param.is_coach = 1
				// #endif
				// #ifdef APP-PLUS
				if (!this.is_app_user) {
					param.is_coach = 1
				}
				// #endif

				let methodType = {
					1: 'login',
					2: 'appLogin',
					3: 'iosLogin'
				}
				let methodModel = methodType[type]
				let user_info = await this.$api.base[methodModel](param)
				// #ifdef APP-PLUS
				if (init == 1) {
					this.updateUserItem({
						key: 'appLogin',
						val: param.data
					})
				}
				// #endif

				let {
					autograph,
					coach_status,
					data
				} = user_info

				this.$util.hideAll()
				this.updateUserItem({
					key: 'isShowLogin',
					val: false
				})
				this.updateUserItem({
					key: 'userInfo',
					val: data
				})
				this.updateUserItem({
					key: 'autograph',
					val: autograph
				})

				console.log(this.userInfo, "====login userInfo")

				if (this.tabInd == 1) {
					this.lockTap = false
					this.submit('register')
					return
				}
				this.$util.back()
				let url = this.loginPage || `/pages/coach-index`
				this.$util.goUrl({
					url,
					openType: `reLaunch`
				})
			},
			//表单验证
			validate(param, subType) {
				let validate = new this.$util.Validate();
				this[`${subType}Rule`].map(item => {
					let {
						name,
					} = item
					if (item.name === 'phone_code' && !this.configInfo.coach_account_phone_status) return
					validate.add(param[name], item)
				})
				let message = validate.start();
				return message;
			},
			async submit(subType) {
				let {
					authTime
				} = this
				if (authTime && subType == 'send') return 
				let param = this.$util.deepCopy(subType == 'send' ? this.registerForm : this[`${subType}Form`])
				let msg = this.validate(param, subType);
				if (msg) {
					this.$util.showToast({
						title: msg
					})
					return
				}
				if (subType === 'register' && param.pass_again != param.pass_word) {
					this.$util.showToast({
						title: `两次密码输入不一致`
					})
					return
				}
				if (subType === 'register' && !this.autograph) {
					// #ifdef APP-PLUS
					if (this.is_ios_login) {
						this.$refs.show_rule_item.open()
					} else {
						this.toChooseLogin('weixin')
					}
					// #endif
					// #ifndef APP-PLUS
					this.toChooseLogin('weixin')
					// #endif
					return
				}
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				try {
					let methodArr = {
						send: ['base', 'coachAccountSendShortMsg'],
						register: ['base', 'setCoachAccount'],
						login: ['base', 'coachAccountLogin']
					}
					let methodKey = methodArr[subType][0]
					let methodModel = methodArr[subType][1]
					if (subType == 'send') {
						param = {
							phone: param.user_name
						}
					}
					let loginInfo = await this.$api[methodKey][methodModel](param)
					this.$util.hideAll()
					this.lockTap = false
					if (subType == 'send') {
						this.$util.showToast({
							title: '发送成功'
						})
						this.registerForm.phone_code = ''
						let time = 60
						this.timer = setInterval(() => {
							if (time === 0) {
								clearInterval(this.timer)
								return
							}
							time--
							this.authTime = time
						}, 1000)
						return
					}
					this.timer && clearInterval(this.timer)
					let pageUrl = this.loginPage || `/pages/coach-index`
					if (subType === 'login') {
						this.$util.showToast({
							title: '登录成功'
						})
						this.updateUserItem({
							key: 'autograph',
							val: loginInfo.autograph
						})
						this.updateUserItem({
							key: 'userInfo',
							val: loginInfo.data
						})
						this.updateUserItem({
							key: 'isRegister',
							val: false
						})
						setTimeout(() => {
							this.$util.goUrl({
								url: pageUrl,
								openType: `reLaunch`
							})
						}, 1000)
						return
					}
					this.updateUserItem({
						key: 'isRegister',
						val: true
					})
					await this.getAccountCoach()
					setTimeout(() => {
						let {
							id: coach_id = 0
						} = this.coachAccountInfo
						if (coach_id) {
							this.loginForm = {
								user_name: '',
								pass_word: ''
							}
							this.registerForm = {
								user_name: '',
								phone_code: '',
								pass_word: '',
								pass_again: ''
							}
						}
						let pageParams = ``
						if (pageUrl.includes('?')) {
							pageParams = '?' + pageUrl.split('?')[1]
						}
						// 新用户注册后，账号无效。需成为技-师后再注册才能绑定账号
						this.$util.goUrl({
							url: coach_id ? `/technician/pages/bind-technician?id=${loginInfo}` :
								`/technician/pages/apply${pageParams}`,
							openType: `reLaunch`
						})
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #fff;
		height: 100%;
	}


	.pages-user-login {
		.coach-bg {
			top: 0;
			left: 0;
			width: 100%;
			height: 401rpx
		}

		.logo-img {
			width: 100rpx;
			height: 100rpx;
		}

		.logo-img.md {
			width: 130rpx;
			height: 130rpx;
		}

		.line {
			left: 0;
			top: 60rpx;
			width: 60rpx;
			height: 7rpx;
			border-radius: 7rpx;
		}

		.other-sign {
			width: 328rpx;
			height: 60rpx;

			.f-mini-title {
				height: 60rpx;
				color: #142C57
			}
		}

		.b-1px-t::before {
			top: 29rpx;
			border-top: 1rpx solid #677792;
			color: #677792;
		}

		.sign-icon-btn {
			width: 76rpx;
			height: 76rpx;

			.iconfont {
				font-size: 40rpx;
			}
		}

		.sign-icon-btn.abs {
			opacity: 0.1;
		}

		.btn-item {
			width: 220pt;
			height: 44pt;
			font-size: 15pt;
			border: 1rpx solid #000;
			transform: rotateZ(360deg);

			.iconfont {
				font-size: 19pt;
			}
		}

		.wechat {
			border: none;
			font-size: 13pt;
			box-shadow: 0 18rpx 9rpx 0 rgba(0, 188, 82, 0.07);
		}

		.apple {
			margin-top: 40rpx;
		}

		.login-btn {
			width: 630rpx;
			height: 110rpx;
			color: #142C57;
			background: #F6F7FB;

			.text {
				width: 140rpx
			}

			.input {
				height: 110rpx;
			}

			.iconxianshimima {
				font-size: 30rpx;
			}

			.iconyincangmima {
				font-size: 16rpx;
			}

		}
	}
</style>